<!-- 搜索结果页面 -->
<template>
  <div class="search-result-container">
    <div class="search-header">
      <h2>搜索结果: "{{ keyword }}"</h2>
      <div class="result-count">找到 {{ totalElements }} 个相关课程</div>
    </div>

    <!-- 课程列表 -->
    <div class="courses-grid">
      <CourseCard
        v-for="course in courses"
        :key="course.courseId"
        :course="course"
      />
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="16"
        :total="totalElements"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import CourseCard from '@/components/course/CourseCard.vue'
import request from '@/utils/request'

const route = useRoute()
const keyword = ref('')
const courses = ref([])
const currentPage = ref(1)
const totalElements = ref(0)

// 获取搜索结果
const fetchSearchResults = async () => {
  try {
    console.log('发起搜索请求，关键词:', keyword.value)
    const response = await request({
      url: '/searchService/search/searchCourse',
      method: 'post',
      data: {
        keyword: keyword.value,
        page: currentPage.value 
      }
    })

    if (response.code === 200 && response.data) {
      courses.value = response.data.content
      totalElements.value = response.data.totalElements
    }
  } catch (error) {
    console.error('获取搜索结果失败:', error)
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchSearchResults()
}

// 监听路由参数变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    keyword.value = newKeyword
    currentPage.value = 1 // 重置页码
    fetchSearchResults()
  }
}, { immediate: true })

// 组件挂载时获取搜索关键词并执行搜索
onMounted(() => {
  keyword.value = route.query.keyword || ''
  fetchSearchResults()
})
</script>

<style scoped>
.search-result-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  margin-bottom: 30px;
}

.search-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.result-count {
  color: #666;
  font-size: 14px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style> 